package com.young.controller;

import com.young.config.SysConfig;
import com.young.entity.User;
import com.young.exception.ValidateCodeExpiredException;
import com.young.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.Mapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 描述:
 *
 * @author BluceYoung
 * @create 2020-11-29 15:30
 * B站：TeacherYoung凌风
 * www.teacheryoung.com
 */
@Controller
public class MainController {

    @Autowired
    UserService userService;

    @GetMapping(value = {"/","/index.html"})
    public String index(){
        return "index";
    }

    @GetMapping(value = {"/register.html"})
    public String register(){
        return "register";
    }

    @PostMapping(value = {"/register.html"})
    public String doregister(User user, HttpServletRequest request){
        //获取请求的ip地址
        user.setRegisterIp(request.getRemoteAddr());
        boolean result = false;
        try {
            result = userService.register(user);
            request.setAttribute("msg","注册成功");
        } catch (MessagingException e) {
            e.printStackTrace();
            request.setAttribute("msg","注册失败");
        }
        return "register";
    }

    @GetMapping("/login.html")
    public String login(){
        return "login";
    }

    @PostMapping("/login.html")
    public String dologin(String loginMail, String pwd, Model model, HttpSession session){

        User user = userService.login(loginMail, pwd);
        if(user==null){//登录失败
            model.addAttribute("msg","用户名或密码错误");
        }else{//登录成功
            if(user.getStatus()==0){//未激活
                model.addAttribute("msg","需激活|"+user.getId());
            }else{//已激活
                session.setAttribute(SysConfig.SESSION_USER,user);
                return "redirect:/index.html";
            }
        }
        return "login";
    }

    @GetMapping(value = "/active", produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public String active(Long userId,String code){
        try {
            boolean result = userService.active(userId, code);
            if(result){
                return "激活成功，请重新登录";
            }else{
                return "验证码错误，请重新去邮箱确认";
            }
        } catch (ValidateCodeExpiredException e) {
            return e.getMessage();
        }
    }

    @GetMapping("/logout.html")
    public String logout(HttpSession session){
        //让session失效
        session.invalidate();
        return "redirect:/login.html";
    }
}
